/**
 * LehuOptimizer - for a faster, safer and more compatible Lehu BBS
 * @author XiaoSK
 */

// Common log in console
function printLog(code) {
	console.group("LehuOptimizer Message")
	console.log("XSS was detected on this page and has been intercepted.")
	console.log("Detail: " + code);
	console.groupEnd();
}

// Inject script to intercept inline JS calls in td.articlecontent
function hookEvent(onevent) {
	document.addEventListener(onevent.substr(2), function(e) {
		var element = e.target;
		if (element.nodeType != Node.ELEMENT_NODE ||
			document.querySelector("div.vote_click a") == element ||
			document.querySelector("div.VoteResult #formVote button[type=submit]") == element) {
			return;
		}
		var f = document.querySelectorAll("td.articlecontent, .center .sect, .topicList .topic, .message, .module1 .list");
		for(var j = 0; j < f.length; j++) {
			if(f[j].nodeType == Node.ELEMENT_NODE && f[j].contains(element)) {
				var code = element.getAttribute(onevent);
				if(code) {
					element[onevent] = null;
					e.preventDefault();
					e.stopImmediatePropagation();
					printLog(code);
					break;
				}
			}
		}
	}, true);
}
for(var k in document) {
	if (/^on/.test(k)) {
		hookEvent(k);
	}
}

// Moniter and intercept Data URI/Src JS/Flash XSS
if(document.querySelectorAll("td.articlecontent").length > 0) {
	var observer = new MutationObserver(function(mr) {
		mr.forEach(function(m) {
			var n = m.addedNodes;
			for(var i in n) {
				if( (n[i].nodeName == "OBJECT" && n[i].data) ||
					(n[i].nodeName == "IFRAME" && n[i].src.indexOf("http://") != 0) ||
					(n[i].nodeName == "EMBED" && n[i].allowScriptAccess && n[i].allowScriptAccess == "always") ||
					(n[i].nodeName == "EMBED" && n[i].src && n[i].src.indexOf("http://") != 0 && n[i].src.indexOf("https://") != 0 && n[i].src.indexOf("ftp://") != 0) ||
					(n[i].nodeName == "PARAM" && n[i].name.toLowerCase() == "allowscriptaccess") ) {
					printLog("<" + n[i].nodeName + "> element contains executable script");
					n[i].parentNode.removeChild(n[i]);
				}
			}
		});
	});
	observer.observe(document, {
		subtree: true,
		childList: true
	});
}
